package org.smart4j.framework.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 处理json与pojo之间的转换
 * @author luoyong
 * @date 2018-11-19下午 9:06
 */
public final class JsonUtil {

    private static  final Logger LOGGER = LoggerFactory.getLogger(JsonUtil.class);

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 将pojo 装换成json
     * @param obj pojo
     * @param <T> 泛型
     * @return json字符串
     */
    public static <T> String toJson(T obj){
        String json;
        try {
            json = OBJECT_MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            LOGGER.error("convert pojo to json failure",e);
            throw  new RuntimeException(e);
        }
        return  json;
    }

    /**
     * json 转 pojo
     * @param json json
     * @param type type
     * @param <T> 泛型
     * @return pojo
     */
    public static <T> T fromJson(String json,Class<T> type){

        T pojo;
        try {
            pojo = OBJECT_MAPPER.readValue(json,type);
        } catch (Exception e) {
            LOGGER.error("convert json to pojo failure",e);
            throw  new RuntimeException(e);
        }
        return pojo;


    }

}
